package com.example.shiro_realy.config;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;


import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Set;

public class CustomRolesOrAuthorizationFilter extends AuthorizationFilter {
    @SuppressWarnings("unchecked")
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        //获取角色集合
        String[] rolesArray = (String[]) mappedValue;
        if (rolesArray == null || rolesArray.length==0) {
            return true;
        }
        //删除角色重复的内容
        Set<String> roles = CollectionUtils.asSet(rolesArray);
        //遍历角色集合，若subject中有roles中的任意一个，则可以访问
        for (String role: roles) {
            if (subject.hasRole(role)) {
                return true;
            }
        }
        return false;
    }
}
